<template>
	<div>
		<v-affix>
			<div class="search-container">
				<search-box></search-box>
			</div>
		</v-affix>
		

		<div class="page-container">
			<div>
				<div class="tag-title">热门标签：</div>
				<div class="tag-items-container">
					<span class="cat-tag" v-for="tag in tags" :key="tag.id" @click="searchKeyWord(tag.itemTitle)">{{tag.itemTitle}}</span>
				</div>
			</div>

			<div style="margin-top: 10px;">
				<div class="tag-title">热门商品：</div>
				<v-spin class="spin-style" :spinning="spinning" tip="商品查询中。。。"></v-spin>
				<div class="tip-style" style="margin-top: 30%;" v-show="showTip">没有查询到相关商品</div>
				<div class="item-container">
					<div style="width: 48%;" ref="left">
						<item-card v-for="item in leftItems" :key="item.key" :itemInfo="item"></item-card>
					</div>
					<div style="width: 48%;" ref="right">
						<item-card v-for="item in rightItems" :key="item.key" :itemInfo="item"></item-card>
					</div>
				</div>
			</div>
			<v-spin class="spin-bottom-style" :spinning="bottomSpinning" tip="查询中。。。"></v-spin>
			<div class="tip-style" v-show="showBottomTip">没有更多了</div>
		</div>

		<home></home>
		
		
	</div>
</template>

<script>
import wx from 'weixin-js-sdk'
export default{
	data(){
		return {
			navId: 0,
			catId: '',
			catName: '',
			tags: [],
			// shopItems: [],
			newItems: [],
			leftItems: [],
			rightItems: [],
			spinning: false,
			showTip: false,
			currentPageNo: 1,
			bottomSpinning: false,
			showBottomTip: false,
			onLoading: false,
		}
	},

	created: function() {

	},

	mounted: function() {
		// console.log(this.$route.query.nav_id)
		this.navId = this.$route.query.nav_id
		this.catId = this.$route.query.cat_id
		this.catName = this.$route.query.cat_name
		this.scroll()
		// this.getNavItems()
		// this.getShopItems()
		// this.getSignPackage()
	},


	activated: function() {
		this.navId = this.$route.query.nav_id
		this.catId = this.$route.query.cat_id
		this.catName = this.$route.query.cat_name
		this.scroll()
		this.getSignPackage()
	},

	watch: {
		catName() {
			this.tags = []
			this.newItems = []
			this.leftItems = []
			this.rightItems = []
			this .spinning = false
			this.showTip = false
			this.currentPageNo = 1
			this .bottomSpinning = false
			this.showBottomTip = false
			this.onLoading = false
			this.getNavItems()
			this.getShopItems()
			this.getSignPackage()
		}
	},

	methods: {
		getNavItems: function() {
			let that = this
			this.axios.get(`/conf/nav_items?nav_id=${this.navId}`)
				.then(response=>{
					// console.log(response.data)
					that.tags = response.data
				})
		},

		getShopItems: function() {
			let that = this
			// console.log(this.catId)
			// console.log(this.catName)
			console.log(this.currentPageNo)
			console.log(this.onLoading)
			// this.spinning = true
			// this.switchLoading()
			this.axios.get(`/api/item/coupon?platform_id=1&cat_id=${this.catId}&q=${this.catName}&page_no=${this.currentPageNo}`)
				.then(response=>{
					// console.log(response.data)

					if (response.data.error) {
                        console.log(response.data.error)
						return
                    }
                    // console.log(response.data.tbk_dg_material_optional_response.result_list.map_data)
                    let items = response.data.tbk_dg_material_optional_response.result_list.map_data
                    for (let i=0; i<items.length; i++) {
                        let item = items[i]
                        // 通过商品是否有优惠券用来算出商品的最终价格
                        let coupon_final_price = item.coupon_amount ? (parseFloat(item.zk_final_price)-parseFloat(item.coupon_amount)).toFixed(2) : (parseFloat(item.zk_final_price)).toFixed(2)
                        item.coupon_final_price = coupon_final_price
                        that.newItems.push(item)
                    }

					that.refreshPageItems()
					// that.switchLoading()
					that.currentPageNo += 1
					this.onLoading = false
				})
		},

		refreshPageItems: function() {
			if (!this.$refs.left || !this.$refs.right) {
				return
			}
			let leftHight = this.$refs.left.clientHeight
			let rightHight = this.$refs.right.clientHeight
			// console.log(`${leftHight}=========${rightHight}`)
			let item = this.newItems.shift()
			if (item == null) {
				return
			}
			if (leftHight <= rightHight) {
				item.key = `left-${this.leftItems.length}`
				this.leftItems.push(item)
			} else {
				item.key = `right-${this.rightItems.length}`
				this.rightItems.push(item)
			}
			let that = this
			this.$nextTick(function() {
				that.refreshPageItems()
			})
		},

		scroll: function() {
			let that = this

			window.addEventListener('scroll', function() {
				// console.log("scrollTop:" + document.documentElement.scrollTop)
				// console.log("scrollY:" + window.scrollY)
				// console.log("offsetHeight:" + document.documentElement.offsetHeight)
				if (!that.onLoading && (document.documentElement.offsetHeight + window.scrollY + 100 >= document.documentElement.scrollHeight)){
					that.onLoading = true
					console.log("滚动到底部了。。。")
					that.getShopItems()
				}
			})

			// window.onscroll = function() {
			// 	// console.log("offsetHeight:" + document.documentElement.offsetHeight)
			// 	// console.log("scrollTop:" + document.documentElement.scrollTop)
			// 	// console.log("scrollHeight:" + document.documentElement.scrollHeight)
			// 	// console.log("scroll=====================")
			// 	// console.log(document.documentElement.offsetHeight + document.documentElement.scrollTop)
			// 	// console.log(document.documentElement.scrollHeight)
			// 	// console.log(`onLoading----${that.onLoading}`)
			// 	if (!that.onLoading && (document.documentElement.offsetHeight + document.documentElement.scrollTop + 100 >= document.documentElement.scrollHeight)){
			// 		that.onLoading = true
			// 		console.log("滚动到底部了。。。")
			// 		that.getShopItems()
			// 	}
			// }
		},

		switchLoading: function() {
			if (this.currentPageNo > 1) {
				this.bottomSpinning = !this.bottomSpinning
			} else {
				this.spinning = !this.spinning
			}
		},

		showTipBox: function() {
			if (this.currentPageNo > 1) {
				this.showBottomTip = true
			} else {
				this.showTip = true
			}
		},

		searchKeyWord: function(keyWord) {
			this.$router.push({path: 'search-res', query: {key_word: keyWord}})
		},

		getSignPackage: function() {
			let currentUrl = window.location.href
			console.log(currentUrl)
			let urlArr = currentUrl.split("#")
      		let url = encodeURIComponent(urlArr[0])
			this.axios.get(`getAccess.php?url=${url}`)
				.then(res => {
					console.log(res)
					this.setWxConfig(res.data)
				})
				.catch(error => {
					console.log(error)
				})
		},

		setWxConfig: function(data) {
			let catName = this.catName
			let currentUrl = window.location.href
			let urlArr = currentUrl.split("#")
      		let url = encodeURIComponent(urlArr[0])
			wx.config({
				debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
				appId: data.appId, // 必填，公众号的唯一标识
				timestamp: data.timestamp, // 必填，生成签名的时间戳
				nonceStr: data.nonceStr, // 必填，生成签名的随机串
				signature: data.signature,// 必填，签名
				jsApiList: [
					'onMenuShareTimeline',
					'onMenuShareAppMessage'
				] // 必填，需要使用的JS接口列表
			});
			wx.ready(function() {
				console.log('接口配置信息已经完成')
				wx.onMenuShareTimeline({
					title: catName,
					link: currentUrl,
					imgUrl: 'http://neimengweixin.cdn.xianyugame.com/66game/youhuiquan.jpg',
					success: function() {
						console.log('用户点击按钮回调')
					}
				})

				wx.onMenuShareAppMessage({
					title: catName, // 分享标题
					desc: `点击领取更多【${catName}】优惠券`, // 分享描述
					link: currentUrl, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
					imgUrl: 'http://neimengweixin.cdn.xianyugame.com/66game/youhuiquan.jpg', // 分享图标
					type: '', // 分享类型,music、video或link，不填默认为link
					dataUrl: '', // 如果type是music或video，则要提供数据链接，默认为空
					success: function () {
						// 用户点击了分享后执行的回调函数
						console.log('用户点击了分享给朋友按钮')
					}
				})
			})
		},

	}
}
</script>